// 在 Vue 组件中
export default {
    data() {
      return {
        socket: null,
        messages: []
      };
    },
    mounted() {
      this.socket = new WebSocket('ws://localhost:8080/ws');
      
      // 监听消息
      this.socket.onmessage = (event) => {
        this.messages.push(JSON.parse(event.data));
      };
  
      // 处理错误
      this.socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };
  
      // 连接关闭
      this.socket.onclose = () => {
        console.log('WebSocket 连接关闭');
      };
    },

    methods: {
      sendMessage(message) {
        if (this.socket.readyState === WebSocket.OPEN) {
          this.socket.send(JSON.stringify(message));
        }
      }
    },

    beforeDestroy() {
      this.socket.close(); // 组件销毁时关闭连接
    }
  };